package com.zhisuo.apicenter.util;

import com.alibaba.fastjson.JSONObject;
import com.zhisuo.apicenter.Constants;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.URL;
import java.security.NoSuchAlgorithmException;


public class WxCommonUtil {

	// 获取unionid
	public final static String getunionid = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";

	public final static String getwxcode = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN";

	/**
	 * 获取UNIONID
	 */
	public static String getUNIONID(String appid, String secret, String jscode) {
		String requestUrl = getunionid.replace("APPID", appid).replace("SECRET", secret).replace("JSCODE", jscode);
        //System.out.println("requestUrl-------"+requestUrl);
		JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
		//System.out.println("jsonObject----"+jsonObject.toString());
		if (null != jsonObject) {
			return jsonObject.toString();
		} else {
			return null;
		}

	}

//	private final Gson GSON = new GsonBuilder().disableHtmlEscaping().create();

	/**
	 * 获取wxcode
	 * @throws FileNotFoundException 
	 */
//	public static String getWxCode(String token, String path,String scene) throws Exception {
//		String requestUrl = getwxcode.replace("ACCESS_TOKEN", token);
//
//		RestTemplate rest = new RestTemplate();
//		InputStream inputStream = null;
//		OutputStream outputStream = null;
//		Map<String, Object> param = new HashMap<>();
//		param.put("scene",scene);
//		param.put("page", "pages/home/index/index");
//		param.put("width", 430);
//		param.put("auto_color", false);
//
//		MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
//		HttpEntity requestEntity = new HttpEntity(param, headers);
//		ResponseEntity<byte[]> entity = rest.exchange(requestUrl, HttpMethod.POST, requestEntity, byte[].class,
//				new Object[0]);
//		System.out.println(entity.getBody().toString());
//		byte[] result = entity.getBody();
//		inputStream = new ByteArrayInputStream(result);
//		String filename = System.currentTimeMillis() + RandomStringUtils.random(4, "1234567890")+".png";
//		File file = new File(Constants.IMAGEFILE+filename);
//		if (!file.exists()) {
//			file.createNewFile();
//		}
//		outputStream = new FileOutputStream(file);
//		int len = 0;
//		byte[] buf = new byte[1024];
//		while ((len = inputStream.read(buf, 0, 1024)) != -1) {
//			outputStream.write(buf, 0, len);
//		}
//		outputStream.flush();
//		return filename;
//	}

	/**
	 * 
	 * @param requestUrl
	 * @param requestMethod
	 * @param outputStr
	 * @return
	 */
	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;

		try {
			TrustManager[] tm = { new MyX509TrustManager() };

			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

			sslContext.init(null, tm, new java.security.SecureRandom());

			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);

			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

			conn.setSSLSocketFactory(ssf);

			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod(requestMethod);

			if (null != outputStr) {

				OutputStream outputStream = conn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream = conn.getInputStream();

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			jsonObject = JSONObject.parseObject(buffer.toString());

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return jsonObject;

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(getUNIONID(Constants.WXAPP_ID,Constants.WXPAYAPI_SECRET,"021PkKll2aPkJ54sP0ll2EMyVE0PkKlg"));

	}

}
